<template>
  <base-breadcrumb v-if="routerAlive" :breadcrumb="!isAudit">
    <div class="about-master-container">
      <b-steps :current="stepVal" direction="vertical" @change.self="stepChange">
        <b-step title="基本信息">
          <a-card v-show="activeKey[0]" slot="description" v-loading="loading.one" :bordered="false">
            <a-form-model ref="basicForm" :model="formData" :rules="formRules">
              <a-row>
                <a-col :span="8">
                  <a-form-model-item label="物资需求总计划编码">
                    <BaseInput v-model="formData.masterPlanCode" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="项目名称" prop="projectCode">
                    <SelectDownProject v-model="formData.projectCode" :disabled="state === 3"
                      @input="getProjectPerson" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="编号" prop="code">
                    <BaseInput v-model="formData.code" :disabled="state === 3" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="创建人">
                    <BaseInput v-model="formData.creatorName" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="创建时间">
                    <BaseInput v-model="formData.createTime" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="商务工程师">
                    <BaseInput v-model="formData.businessEngineer" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="项目总工">
                    <BaseInput v-model="formData.projectEngineer" disabled />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
            <div v-if="!isAudit" class="pub-next-btn">
              <a-button v-if="state !== 3" type="primary" @click="temporaryStorage()">
                保存草稿
              </a-button>
              <a-button type="primary" @click="temporaryStorage(true)">
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="项目钢筋需用总计划">
          <a-card v-if="activeKey[1]" slot="description" :bordered="false">
            <rebarplantable :id="formData.id" :state="state" />
            <div v-if="!isAudit" class="pub-next-btn">
              <a-button type="primary" @click="previous">
                上一步
              </a-button>
              <a-button type="primary" @click="next">
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="项目混凝土需用总计划">
          <a-card v-if="activeKey[2]" slot="description" :bordered="false">
            <concrete-planTable :id="formData.id" :state="state" />
            <div v-if="!isAudit" class="pub-next-btn">
              <a-button type="primary" @click="previous">
                上一步
              </a-button>
              <a-button type="primary" @click="next">
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="项目物资需用总计划">
          <a-card v-if="activeKey[3]" slot="description" :bordered="false">
            <materail-planTable :id="formData.id" :state="state" />
            <div v-if="!isAudit" class="pub-next-btn">
              <a-button type="primary" @click="previous">
                上一步
              </a-button>
              <a-button type="primary" @click="next">
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="周转工具需用总计划">
          <a-card v-if="activeKey[4]" slot="description" :bordered="false">
            <tool-plan-table :id="formData.id" :state="state" />
            <div v-if="!isAudit" class="pub-next-btn">
              <a-button type="primary" @click="previous">
                上一步
              </a-button>
              <a-button type="primary" @click="next">
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="机械设备需用总计划基本信息">
          <a-card v-if="activeKey[5]" slot="description" v-loading="loading.six" :bordered="false">
            <a-form-model ref="deviceForm" :model="deviceForm" :rules="deviceFormRules">
              <a-row>
                <a-col :span="8" prop="contacts">
                  <a-form-model-item label="联系人" prop="contacts">
                    <a-input-search v-model="deviceForm.contacts" :disabled="state === 3" @search="openPerson"
                      @click="openPerson" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="电话">
                    <BaseInput v-model="deviceForm.phone" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="计划时间" required prop="timeRange">
                    <a-range-picker v-model="deviceForm.timeRange" format="YYYY-MM-DD" :disabled="state === 3" />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-form-model-item label="编号" prop="materialMechanicalNumber">
                    <BaseInput v-model="deviceForm.materialMechanicalNumber" :disabled="state === 3" />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
            <div v-if="!isAudit" class="pub-next-btn">
              <a-button type="primary" v-if="state !== 3" @click="sumbitDeviceBasic">
                保存
              </a-button>
              <a-button type="primary" @click="previous">
                上一步
              </a-button>
              <a-button type="primary" @click="next">
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="机械设备需用总计划">
          <a-card v-if="activeKey[6]" slot="description" :bordered="false">
            <equipment-plan-table :id="formData.id" :state="state" />
            <div v-if="!isAudit" class="pub-next-btn">
              <a-button type="primary" @click="previous">
                上一步
              </a-button>
              <a-button type="primary" @click="next">
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="相关附件">
          <a-card v-if="activeKey[7]" slot="description" :bordered="false">
            <u-table :upload-list="addFile" :delete-url="fileDel" :is-show="state !== 3" :list-url="fileList"
              :business-id="formData.id" business-code="MM06" />
            <div v-if="!isAudit" class="pub-next-btn">
              <a-button type="primary" @click="previous">
                上一步
              </a-button>
            </div>
          </a-card>
        </b-step>
      </b-steps>
      <div v-if="!isAudit" class="pub-header-btn page-btn-right-top">
        <a-button v-if="state !== 3" :loading="loading.one" type="primary" @click="openSubmit">
          提交
        </a-button>
        <a-button v-if="state === 3" type="primary" @click="openHistory">
          历史记录
        </a-button>
        <a-button v-checkVisibleInDetail @click="handleClose">
          关闭
        </a-button>
      </div>
      <history :id="listId" ref="history" />
      <person-list ref="personList" @getPerson="getPerson" />
      <type-dialog ref="typeDialog" @submit="submit" />
    </div>
    <selectApprover :business-id="businessId" :process-config="setProcessConfig" />
  </base-breadcrumb>
</template>

<script>
import rebarplantable from './components/rebarPlan'
import history from './components/history'
import concretePlanTable from './components/concretePlan' // 混凝土
import materailPlanTable from './components/materialPlan' // 物资需用
import toolPlanTable from './components/toolsPlan' // 周转工具
import equipmentPlanTable from './components/equipmentPlan' // 机械设备
import {
  totalPlanListAdd,
  totalPlanListEdit,
  audit,
  addFile,
  fileList,
  fileDel,
  equipmentBasic,
  totalPlanListDetail,
  departmentConfig
} from '@/api/material/materialMasterPlan/materialPlan'
import { themeChoose } from '@/mixin/mixin'
import typeDialog from './components/typeDialog'
import SelectDownProject from '@/components/Select/SelectDownProject'
import { getAuditProject } from '@/api/themeChoose/themeChoose'
import { checkVisibleInDetail } from '@/utils/util'

export default {
  name: 'MaterialMasterPlanAdd',
  components: {
    rebarplantable,
    concretePlanTable,
    materailPlanTable,
    toolPlanTable,
    equipmentPlanTable,
    history,
    typeDialog,
    SelectDownProject
  },
  data() {
    let validateTimeRange = (rule, value, callback) => {
      if (value.some((v) => v == null)) {
        callback(new Error('计划时间不能为空'))
      }
      if (value.length === 0) {
        callback(new Error('计划时间不能为空'))
      }
      callback()
    }
    return {
      routerAlive: true,
      activeKey: [true, false, false, false, false, false, false],
      loading: {
        one: false,
        six: false
      },
      state: Number(this.$route.query.state),
      isSubmit: false,
      row: this.$route.query.row,
      listId:'',
      formData: {
        createTime: this.getNowTime(),
        masterPlanCode: '',
        projectId: null,
        projectCode: '',
        code: null,
        creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
        businessEngineer: '',
        projectEngineer: '',
        projectName: ''
      },
      formRules: {
        projectCode: { required: true, message: '项目名称不能为空', trigger: 'change' },
        code: { required: true, message: '编号不能为空', trigger: 'blur' }
      },
      deviceForm: {
        contacts: '',
        phone: '',
        materialMechanicalNumber: '',
        startDate: '',
        endDate: '',
        timeRange: []
      },
      optionArr: [],
      stepVal: 0,
      isNext: false,
      addFile: addFile(),
      fileDel: fileDel(),
      fileList: fileList(),
      deviceFormRules: {
        contacts: { required: true, message: '联系人不能为空', trigger: 'change' },
        // timeRange:{  type: 'array',required: true, message: '计划时间不能为空', trigger: 'change' },//不生效
        timeRange: [{ validator: validateTimeRange, trigger: 'change' }],
        materialMechanicalNumber: { required: true, message: '编号不能为空', trigger: 'blur' }
      },
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.state = 3
        }
      }
    },
    stepVal(newVal, oldVal) {
      this.$set(this.activeKey, newVal, true)
    },
    $route(newVal, oldVal) {
      if (newVal.path === oldVal.path) {
        let _query = this.$route.query;
        this.routerAlive = false
        this.formData.id = _query.id;
        if (_query.targetPage === 'list'){
          this.listId = _query.id;
        }
        this.getEditInfo()
        this.$nextTick(() => {
          this.routerAlive = true
        })
      }
    }
  },
  async mounted() {
    this.$nextTick(() => {
      if (this.state !== 1) {
        let _query = this.$route.query;
        this.formData.id = _query.id
        if (_query.targetPage === 'list') {
          this.listId = _query.id;
        }
        this.getEditInfo()
        this.isSubmit = true
      }
    })
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('mm_master_plan')
  },
  methods: {
    handleClose() {
      this.$close()
    },
    openPerson: function () {
      this.$refs.personList.open()
    },
    getPerson: function (row) {
      console.log(row)
      this.deviceForm.contacts = row.name
      this.deviceForm.phone = row.phoneNum
    },
    openHistory: function () {
      this.$refs.history.open()
    },
    async getProjectPerson(projectId) {
      let res = await departmentConfig({ projectId })
      // this.$console(val)
      // this.$console(res)
      if (res.code === 200) {
        let person1 = res.data.postConfigList.find((v) => v.jobName === '项目总工')
        if (person1.staffList.length) {
          this.formData.projectEngineer = person1.staffList[0].staffName
        } else {
          this.formData.projectEngineer = '暂无人员'
        }
        let person2 = res.data.postConfigList.find((v) => v.jobName === '商务工程师')
        if (person2.staffList.length) {
          this.formData.businessEngineer = person2.staffList[0].staffName
        } else {
          this.formData.businessEngineer = '暂无人员'
        }
      } else {
        this.$message.warning('获取项目信息失败')
      }
    },
    next: function (val) {
      this.isNext = true
      this.stepVal++
    },
    stepChange: function (val) {
      if (!this.formData.id && !this.isAudit) {
        // 作为审批详情时可跳过步骤
        if (val) {
          this.$message.warning('切换步骤前请先填写基本信息')
          this.stepVal = 0
        }
      } else {
        if (!this.isNext) {
          this.stepVal = val
          this.$set(this.activeKey, val, !this.activeKey[val])
        }
      }
      this.isNext = false
    },
    previous: function () {
      this.isNext = true
      this.stepVal--
      if (this.stepVal < 0) {
        this.stepVal = 0
      }
    },

    // 获取编辑回显数据
    async getEditInfo() {
      this.loading.one = true
      if (this.formData && this.formData.id) {
        let res = await totalPlanListDetail({ id: this.formData.id })
        if (res.code === 200) {
          this.formData = this.$assign(this.formData, res.data)
          this.deviceForm = this.$assign(this.deviceForm, this.formData)
          this.deviceForm.timeRange = []
          this.deviceForm.timeRange.push(this.formData.startDate)
          this.deviceForm.timeRange.push(this.formData.endDate)
          // this.$console(this.deviceForm)
          this.getProjectPerson(this.formData.projectCode)
        }
        this.loading.one = false
      }
    },
    openSubmit: function () {
      if (this.isSubmit) {
        this.$refs.typeDialog.open()
      } else {
        this.$message.warning('提交之前请先暂存')
      }
    },
    submit(val) {
      this.setProcessConfig = null;
      if (this.isSubmit) {
        this.submitApprovalConfirm(this.processConfig, (flag) => {
          if (!flag) {
            this.loading.one = false
            return
          }
          this.loading.one = true
          audit({ baseId: this.formData.id, type: val }).then(
            (res) => {
              this.$message.success('提交成功')
              this.loading.one = false
              // this.$multiTab.close(this.$route.fullpath)
              //提交时，返回id
              this.businessId = res.data.id || this.formData.id;
              this.setProcessConfig = this.processConfig;
            },
            (error) => {
              this.$message.warning(error.data.message)
              this.loading.one = false
            }
          )
        })
      } else {
        this.$message.warning('提交之前请先暂存')
      }
    },
    sumbitDeviceBasic() {
      this.$refs.deviceForm.validate((valid) => {
        console.log(valid)
        if (valid) {
          if (this.deviceForm.timeRange.length) {
            this.deviceForm.startDate = this.getNowTime(this.deviceForm.timeRange[0])
            this.deviceForm.endDate = this.getNowTime(this.deviceForm.timeRange[1])
          }
          this.loading.six = true
          equipmentBasic(this.deviceForm).then((res) => {
            if (res.code === 200) {
              this.$message.success('保存成功')
              this.isSubmit = true
              this.getEditInfo()
            }
            this.loading.six = false
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
          return false
        }
      })
    },
    temporaryStorage(isNext) {
      if (this.state === 3) {
        this.next()
        return
      }
      this.$refs.basicForm.validate(async (valid) => {
        if (valid) {
          this.loading.one = true
          if (this.state === 2 || this.formData.id) {
            if (this.formData.auditStatus !== 'DRAFT') {
              this.formData.auditStatus = 'CHANGE'
            }
            totalPlanListEdit(this.formData).then((res) => {
              console.log(res)
              if (res.code === 200) {
                this.$message.success('编辑成功')
                this.isSubmit = true
                if (isNext) {
                  this.next()
                }
              }
              this.loading.one = false
            })
          } else {
            totalPlanListAdd(this.formData).then((res) => {
              console.log(res)
              if (res.code === 200) {
                this.formData.id = res.data.id
                this.$message.success('保存成功')
                if (isNext) {
                  this.next()
                }
                this.isSubmit = true
                this.getEditInfo()
              }
              this.loading.one = false
            })
          }
        }
      })
    }
  }
}
</script>
